package com.shujia.zookeeper;

import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class Demo2Test {

    ZooKeeper zooKeeper;

    @Before
    public void init() {
        try {
            //创建zk连接
            zooKeeper = new ZooKeeper("master:2181,node1:2181,node2:2181", 30000, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void create() {
        try {

            zooKeeper.create("/zookeeper/test",
                    "zk".getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL //临时节点，连接断开自动删除
            );
        } catch (KeeperException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        try {
            Thread.sleep(100000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void watcher() {
        try {

            List<String> children = zooKeeper.getChildren("/zookeeper/test", new Watcher() {
                public void process(WatchedEvent event) {

                    /**
                     * 监控节点的变化，如果节点发生任何变化，zk会通知客户端，执行回调函数
                     *
                     * 判断事件的类型，如果是delete类型，将当前节点修改为active
                     */
                    System.out.println("临时节点发生变化");
                    System.out.println(event);
                }
            });

            System.out.println(children);

            while (true) {
            }

        } catch (KeeperException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @After
    public void close() {
        try {
            //关闭连接
            zooKeeper.close();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
